package com.usian.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.usian.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

@RestController
public class FileUploadController {

    @Resource
    private FastFileStorageClient storageClient;

    private List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif");

    @RequestMapping("/file/upload")
    public Result fileUpload(MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();

            //校验文件类型
            String contentType = file.getContentType();
            if(!CONTENT_TYPES.contains(contentType)){
                return Result.error("文件类型不合法："+originalFilename);
            }

            //检验文件内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                return Result.error("文件内容不合法："+originalFilename);
            }

            //上传文件
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            //返回图片回显的url
            return Result.ok("http://image.usian.com/"+storePath.getFullPath());
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
}
